package accs.product.license;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

public final class LicenseKey {
	private String key;
	
	public LicenseKey(String key) {
		if(key==null || key.length()==0) throw new IllegalArgumentException("Invalid key.");
		this.key=key;
	}
	
	public static LicenseKey generate() throws SocketException {
		Enumeration<NetworkInterface> list=NetworkInterface.getNetworkInterfaces();
		StringBuilder str=new StringBuilder();		
		
		while(list.hasMoreElements()) {
			NetworkInterface net=list.nextElement();
			byte[] hw=net.getHardwareAddress();
			if(hw!=null && hw.length==6) str.append(Hex.encodeHexString(hw));
		}
		
		if(str.length()==0) return null;
		
		return new LicenseKey(DigestUtils.sha256Hex(str.toString()));
	}
	
	public String toString() {
		return key;
	}
	
	public boolean equals(Object obj) {
		if(!(obj instanceof LicenseKey)) return false;
		
		LicenseKey other=(LicenseKey)obj;
		return this.key.equals(other.key);
	}
}